import { _decorator, Component, Node, quat, Quat, toRadian, v3, Vec3 } from 'cc';
import GameUI from '../UI/GameUI';
import { GameData } from '../Data/GameData';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    private static instance: GameManager;
    static get Instance() {
        return this.instance;
    }

    @property(Node)
    levels: Node;
    @property([Node])
    targets: Node[] = [];

    level: Node;
    q: Quat;
    targetq: Quat;
    targetNum = 0;
    fixTime = 0;
    rotateTime = 0;
    isRotate = false;

    IsTips: boolean = false;

    onLoad() {
        GameManager.instance = this;
    }

    start() {
        var num = GameData.levelNum;
        this.level = this.levels.children[num - 1];
        this.level.active = true;
        if (num == 1) {
            this.IsTips = true;
            GameUI.Instance.showTips();
        }
    }

    update(dt) {
        if (GameUI.Instance.isFinish && GameUI.Instance.failPanel.active) return;
        var forward = this.targets[0].forward;
        var forward2 = this.targets[1].forward;
        var forward3 = this.level.forward;
        var angle = Vec3.angle(forward, forward3);
        var angle2 = Vec3.angle(forward2, forward3);
        if (angle < 0.05 || angle2 < 0.05) {
            this.fixTime += dt;
        }
        else this.fixTime = 0;
        if (this.fixTime >= 0.5) {
            if (angle < 0.05) this.targetNum = 0;
            else this.targetNum = 1;
            GameUI.Instance.Victory();
        }
        if (GameUI.Instance.isFinish) {
            if (this.rotateTime < 1) {
                this.rotateTime += dt;
            }
            else this.rotateTime = 1;
            var q2 = quat();
            Quat.slerp(q2, this.q, this.targetq, this.rotateTime);
            this.level.setWorldRotation(q2);
        }
        if (this.isRotate) {
            if (this.rotateTime < 1) {
                this.rotateTime += dt;
                var q2 = quat();
                Quat.slerp(q2, this.q, this.targetq, this.rotateTime);
                this.level.setWorldRotation(q2);
            }
            else {
                this.rotateTime = 0;
                this.isRotate = false;
                GameUI.Instance.rotatePanel.active = true;
            }
        }
    }

    SetQuat() {
        this.q = this.level.getWorldRotation();
        this.targetq = this.targets[this.targetNum].getWorldRotation(this.targetq);
    }

    Rotate() {
        this.q = this.level.getWorldRotation();
        this.targetq = quat();
        Quat.rotateAround(this.targetq, this.q, Vec3.UP, toRadian(180));
        this.isRotate = true;
    }
}